<template>
	<el-dialog v-model="showModal" class="peak-dialog" :close-on-click-modal="false" :title="title" :width="900">
		<el-form ref="paramsFormRef" class="params-form" :inline="true" label-position="right" label-width="110px" :model="paramsForm" :rules="paramsRules">
			<el-row :gutter="16" justify="start">
				<el-col :span="12">
					<el-form-item class="form-item" label="用户昵称:" prop="nickName">
						<el-input v-model="paramsForm.nickName" placeholder="请输入用户昵称" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="form-item" label="所属机构:" prop="deptId">
						<el-tree-select v-model="paramsForm.deptId" :data="treeData" check-strictly :render-after-expand="false" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="form-item" label="用户账号:" prop="userName">
						<el-input v-model="paramsForm.userName" placeholder="请输入用户账号" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="form-item" label="用户性别:" prop="sex">
						<el-radio-group v-model="paramsForm.sex">
							<el-radio :value="'0'">男</el-radio>
							<el-radio :value="'1'">女</el-radio>
							<el-radio :value="'2'">未知</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="form-item" label="手机号码:" prop="phonenumber">
						<el-input v-model="paramsForm.phonenumber" placeholder="请输入手机号码" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="form-item" label="用户邮箱:" prop="email">
						<el-input v-model="paramsForm.email" placeholder="请输入邮箱" />
					</el-form-item>
				</el-col>

				<el-col v-if="showPwdStatus" :span="12">
					<el-form-item class="form-item" label="用户密码:" prop="password">
						<el-input v-model="paramsForm.password" placeholder="请输入用户密码">
							<template #append>
								<div style="cursor: pointer" @click="handleCreatePwd">生成密码</div>
							</template>
						</el-input>
					</el-form-item>
				</el-col>
				<el-col v-if="showPwdStatus" :span="12">
					<el-form-item class="form-item" label="确认密码:" prop="prePwd">
						<el-input v-model="paramsForm.prePwd" placeholder="请输入确认密码" />
					</el-form-item>
				</el-col>

				<el-col :span="12">
					<el-form-item class="form-item" label="用户角色:" prop="roleId">
						<el-select v-model="paramsForm.roleId" class="el-form-item" placeholder="请选择用户角色">
							<el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="form-item" label="用户状态:" prop="status">
						<el-radio-group v-model="paramsForm.status">
							<el-radio :value="'0'">正常</el-radio>
							<el-radio :value="'1'">停用</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
				<!-- <el-col :span="12">
					<el-form-item class="form-item" label="限制登录次数:" prop="limitLoginNum">
						<el-input v-model="paramsForm.limitLoginNum" placeholder="请输入限制登录次数" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="form-item" label="生效时间:" prop="limitLoginTime">
						<el-date-picker v-model="paramsForm.limitLoginTime" placeholder="请选择生效时间" type="date" value-format="YYYY-MM-DD" />
					</el-form-item>
				</el-col> -->
				<el-col :span="24">
					<el-form-item class="form-item" label="备注信息:" prop="remark">
						<el-input v-model="paramsForm.remark" rows="3" type="textarea" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="handleCancel">取 消</el-button>
				<el-button type="primary" @click="handleSure" v-throttle>确 定</el-button>
			</span>
		</template>
	</el-dialog>
</template>
<script name="EditDictTypeModal" setup>
import global from '@/utils/global'
const emit = defineEmits(['peak-modal-ok'])
import { treeUtil } from '@meta/utils'
import { MD5 } from 'crypto-js'
/*
 *@Description: 初始化数据
 *@Author: liuYuFeng
 *@Date: 2023-02-24 16:52:40
 */
const state = reactive({
	showModal: false,
	title: '',
	paramsFormRef: null,
	showPwdStatus: true,
	roleList: [],
	paramsForm: {
		userId: '',
		nickName: '', //用户昵称
		deptId: '', //归属单位
		phonenumber: '', //手机号码
		email: '', //邮箱
		userName: '', //用户名称
		password: '', //用户密码
		prePwd: '',
		sex: '0', //用户性别
		status: '0', //状态
		roleIds: [], // 角色
		roleId: null,
		remark: '', // 备注
		limitLoginNum: '', //限制登录次数
		limitLoginTime: '', //限制登录时间
	},
	paramsRules: {
		nickName: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
		deptId: [{ required: true, message: '请选择所属结构', trigger: 'blur' }],
		userName: [{ required: true, message: '请输入用户账号', trigger: 'blur' }],
		phonenumber: [
			{ required: true, message: '请输入手机号码', trigger: 'blur' },
			{
				pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
				message: '手机号格式不正确',
			},
		],
		email: [
			{ required: true, message: '用户邮箱不能为空', trigger: 'blur' },
			{ pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '邮箱格式不正确' },
		],
		password: [
			{
				required: true,
				validator: (rule, value, callback) => {
					if (!value) {
						callback(new Error('用户密码不能为空！'))
					} else if (value.length < 8) {
						callback(new Error('密码不能低于8位!'))
					} else if (!/^.*(?=.{8,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/.test(value)) {
						callback(new Error('密码须包含大小写字母、数字、特殊符号@、#、！'))
					} else {
						callback()
					}
				},
				trigger: 'blur',
			},
		],
		prePwd: [
			{
				required: true,
				validator: (rule, value, callback) => {
					if (!value) {
						callback(new Error('确认密码不能为空！'))
					} else if (value != state.paramsForm.password) {
						callback(new Error('两次输入的密码不一致！'))
					} else {
						callback()
					}
				},
				trigger: 'blur',
			},
		],
		roleId: [{ required: true, message: '请选择用户角色', trigger: 'change' }],
	},
	treeData: [],
})
const { showModal, title, showPwdStatus, roleList, paramsForm, paramsRules, paramsFormRef, treeData } = toRefs(state)

/*
 *@Description: 方法method
 *@Author: liuYuFeng
 *@Date: 2023-02-24 15:53:16
 */
const handleSure = () => {
	state.paramsFormRef.validate(valid => {
		if (valid) {
			handleSureOk()
		} else {
			return false
		}
	})
}
const handleSureOk = () => {
	const params = { ...state.paramsForm }
	params.roleIds = [state.paramsForm.roleId]
	delete params.roles
	delete params.dept
	if (state.paramsForm.userId) {
		//编辑
		global.$fetchPostData(`/meta-system/web/v1/sysUser/editUser`, params).then(data => {
			if (data.code == 200) {
				state.showModal = false
				emit('peak-modal-ok', 2)
			} else {
				global.$baseMessage(data.msg, 'error')
			}
		})
	} else {
		global
			.$fetchPostData(`/meta-system/web/v1/sysUser/addUser`, {
				...params,
				password: MD5(params.password).toString(),
				prePwd: MD5(params.password).toString(),
			})
			.then(data => {
				if (data.code == 200) {
					state.showModal = false
					emit('peak-modal-ok', 1)
				} else {
					global.$baseMessage(data.msg, 'error')
				}
			})
	}
}
const handleCancel = () => {
	state.showModal = false
}
const handleShowModal = async row => {
	state.showModal = true
	await nextTick()
	getRoleListData()
	getOrgListData()
	state.paramsForm.userId = ''
	if (row) {
		state.title = '编辑用户'
		state.paramsFormRef.resetFields()
		state.showPwdStatus = false
		getDataDetail(row.userId)
	} else {
		state.title = '添加用户'
		state.showPwdStatus = true
		state.paramsFormRef.resetFields()
	}
}
const getDataDetail = userId => {
	global.$fetchPostData(`/meta-system/web/v1/sysUser/details`, { idLong: userId }).then(data => {
		if (data.code == 200) {
			state.paramsForm = data.data || {}
			state.paramsForm.deptId = data.data.dept.deptId
			state.paramsForm.roleIds = data.data.roles.map(item => item.roleId)
			state.paramsForm.roleId = state.paramsForm.roleIds.length > 0 ? state.paramsForm.roleIds[0] : null
		} else {
			global.$baseMessage(data.msg, 'error')
		}
	})
}
//业务接口
const handleCreatePwd = () => {
	global.$fetchPostData(`/meta-system/web/v1/sysUser/createPwd`, {}).then(data => {
		if (data.code == 200) {
			state.paramsForm.password = data.data
		} else {
			global.$baseMessage(data.msg, 'error')
		}
	})
}
const getRoleListData = () => {
	global.$fetchPostData(`/meta-system/web/v1/sysRole/optionselect`, {}).then(data => {
		if (data.code == 200) {
			state.roleList = data.data
		} else {
			global.$baseMessage(data.msg, 'error')
		}
	})
}
const getOrgListData = () => {
	global.$fetchPostData(`/meta-system/web/v1/sysDept/list`, {}).then(data => {
		if (data.code == 200) {
			const treeList = data.data.map(item => ({
				label: item.deptName,
				value: item.deptId,
				parentId: item.parentId,
			}))
			state.treeData = treeUtil.handleTree(treeList, 'value', 'parentId')
		} else {
			global.$baseMessage(data.msg, 'error')
		}
	})
}

defineExpose({
	handleShowModal,
})
</script>
<style lang="scss" scoped></style>
